const app = getApp()

const WXAPI = require('../../wxapi/main');
const strokesHelper = require('../../wxapi/StrokesHelper');
const userSocket = require('../../wxapi/shareSocket');
const StrokesHelper = require('../../wxapi/StrokesHelper');

let timestamp = Date.parse(new Date());
timestamp = timestamp / 1000;
let onlyOnce = 0
let onceTime = 0
let saving = false
const MAX_CACHE_TO_CANVAS_POINT_NUM = 12;

let pointsCache = []
let prePoint = undefined
const canvasDown = 0
const canvasMove = 2
let array_index = 0
let arr11 = []

let tempPages = []

let noteBg = '';
var animation;
var timer;

var prepareAdjustPoint = [];
var isSingleanchor = true;
const innerAudioContext = wx.createInnerAudioContext()

let oneWordPos = [];//new strokesHelper.StrokesStore();
let oneStroke = [];
var lastDrawCanvasName = '';//上次绘画的 canvas 名字

let isAdjustRed = false;//是否重新
let isAdustPointAlready = false;

let classInfo =  6;
let pageNo = 0;

var rm = wx.getRecorderManager();
  //录音停止时调用
  rm.onStop(function(e) {
    console.log(e)
      var a = this;
      wx.showLoading({
        title: "正在识别..."
      });
      //上传逻辑
      var n = {
          url: app.globalData.urlMp3,
          filePath: e.tempFilePath,
          name: "file",
          header: {
            "Content-Type": "application/json"
          },
          formData: {
            token: app.globalData.token,
            'page':  app.globalData.randomNum
          },
          success: function (res) {
            wx.hideLoading({
              complete: (res) => {},
            })
            wx.showToast({
              title: '成功',
              icon: 'success',
              duration: 1500
            })
          }
        };
        wx.uploadFile(n);
    });

    rm.onPause(function(e) {
      console.log(e)
        var a = this;
        //上传逻辑
        var n = {
            url: app.globalData.urlMp3,
            filePath: e.tempFilePath,
            name: "file",
            header: {
              "Content-Type": "application/json"
            },
            formData: {
              token: app.globalData.token,
              'page':  app.globalData.randomNum
            },
            success: function (res) {
            }
          };
          wx.uploadFile(n);
      });


var TEST_SHOW_ID = 0X01000000;
var last_penStatus;
var last_penX;
var last_penY;
var drawIsShow=false;
var uuID;
var PenStatus_Hover = 0;
var PenStatus_Down = 1;
var PenStatus_Move = 2;
var PenStatus_Up = 3;
var PenStatus_Leave = 4;

var CmdId = {
  PenStatus: 0,
  X: 1,
  Y: 2, 
  Pressure: 3,
  Type: 4,
};

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

Page({
  nowPgae: 1,
  startX: 0,
  slider: false,
  animationData: {},
  ani: {},
  cardInfoList: [{ name: 1 }, { name: 2 }, { name: 3 }, { name: 4 }],
  penData: '',
  lastX: -1,
  lastY: -1,
  ctx: wx.createCanvasContext('partyCanvas'),
  ratio: 6.6,
  ratioX: '',
  ratioY: '',
  data: {
    tian_package_icon: 'circle',
    tian_detail_icon:'circle',
    tian_ogg_icon:'circle',
    tian_draw_icon:'circle',
    tian_prepare_display:'',//拍照后进度区
    classInfo:'',
    pageNum:'',
    semester:'',
    prompt_red_file:"https://wx.ndmooc.com/files/fontdata/pagelogo.jpg",
    prompt_red_image_display:"none",
    tian_detail_info:'',
    tian_draw_info:'',
    prompt_red_display:"block",//图片提示区
    wImage: 0,
    hImage: 0,
    tImage: 0,
    lImage: 0,
    wText: 0,
    hText: 0,
    tText: 0,
    lText: 0,
    avatarImg: '',
    username: '',
    time: 600000,
    hasRecord: false,
    isDot: "block",
    isTouchStart: false,
    isTouchEnd: false,
    value: '100',
    touchStart:0,
    touchEnd:0,
    vd:'',
    recodeFile: false,
    colors_top: [
      {
        color: 'rgb(236, 84, 99)'
      },
      {
        color: 'rgb(171, 146, 238)'
      },
      {
        color: 'rgb(75, 137, 22)'
      },
      {
        color: 'rgb(79, 190, 231)'
      },
      {
        color: 'rgb(162, 210, 102)'
      },
      {
        color: 'rgb(250, 111, 83)'
      },
      {
        color: 'rgb(253, 202, 37)'
      },
      {
        color: 'rgb(69, 207, 173)'
      },
      {
        color: 'rgb(140, 99, 79)'
      },
      {
        color: 'rgb(49, 54, 57)'
      }
    ],
    height: 600,
    recognizerResult: '',
    mp3: '',
    bgm: false,
    fontValue: 0,
    notesbg: [
      {
        _id: 1,
        url: 'https://wx.ndmooc.com/files/moban/dangjian/1.jpg',
        name: '',
        user_id: ''
      },
      // {
      //   _id: 2,
      //   url: 'https://wx.ndmooc.com/files/moban/dangjian/2.jpg',
      //   name: '',
      //   user_id: ''
      // },
      // {
      //   _id: 3,
      //   url: 'https://wx.ndmooc.com/files/moban/dangjian/3.jpg',
      //   name: '',
      //   user_id: ''
      // },
      // {
      //   _id: 4,
      //   url: 'https://wx.ndmooc.com/files/moban/dangjian/4.jpg',
      //   name: '',
      //   user_id: ''
      // }
    ],
    bgShow: false,
    colorNum: '',
    canvasbg: '',
    canvasw: 414,
    canvash: 550,
    lineWidth: 2,
    bgm: false,
    imgUrl: '',
    _id: '',
    mp3: '',
    public: '',
    describe: '',
    shwoBordr: '',
    state: '',
    ftcolor: 'rgb(0,0,0)',
    savedImgUrl: '',
    canvasShow: '',
    btuBottom: '',
    pageId: '',
    imgTurn: '',
    backImg: '',
    clientSize: '',
    paddingClient: '',
    devices: [],
    connected: false,
    chs: [],
    recoderAuthStatus : false,
    joinRoomMd5:'c136bd357ca255b47c0e1e0ed3ec4080',   //加入socket房间时的md5值
    code:'',   //微信登录code
    hasAuthorize:false,  //是否授权
    doodlemsg:'',   //聊天信息
    like_left:0,   //点赞图标left
    like_top:0,   //点赞图标top
    zanZindex:9,  //点赞图片的层级，防止遮挡点击事件
    zanOpacity:0,  //透明度
    spreakingAnimation: {},//放大动画  
    smallAnimation:{},  //动画缩小
    timers:'',  //动画定时器清除 
    roomid:'',  //房间id
    myStreaming:[],//我的流化笔记
    drawingMySHandler:null,
    tianRoomId:'',
    curDrawingPos:0,
    intervalTime:200,
    isShareZone:false,//是否分享进入
    myetag:'',   //我的唯一识别id
    avator:'../../images/user.png',  //用户头像
    writerAvator:'../../images/user.png', //书写者头像   
    writerNickname:'', //书写者昵称 
    writerId:'', //书写者id 
    redNum:0,  //点赞数
    visitNum:0,  //观看数
    cuePraise:false,  //点赞弹窗
    chatBtn_default:1,  //消息输入框 1为默认样式 2为弹起样式 
    showChatList:false,  //查看聊天列表
    chatTotal:0,   //聊天总数
    chatlist:[],  //聊天消息
    beforeFocus:1,  //键盘被唤起之前的状态
  },
  // 背景音乐
  BGM: function (e) {
    let that = this;
    if (that.data.bgm) {
      that.setData({
        bgm: false,
      })
      innerAudioContext.pause(); /**  暂停音乐 */

    } else {
      that.setData({
        bgm: true,
        bgmImgAni: "bgmImgAni"
      })
      // 播放音乐
      innerAudioContext.autoplay = true
      innerAudioContext.loop = true
      innerAudioContext.src = that.data.mp3;
      innerAudioContext.play()
    }
  },
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  mornThin(e) {
    this.setData({
      colorNum: e.currentTarget.dataset.id,
      bgShow: (!this.data.bgShow),
      lineWidth: 1
    })
    context.setLineWidth(1);
  },
  middleThin(e) {
    this.setData({
      colorNum: e.currentTarget.dataset.id,
      bgShow: (!this.data.bgShow),
      lineWidth: 2
    })
    context.setLineWidth(2);
  },
  largeThin(e) {
    this.setData({
      colorNum: e.currentTarget.dataset.id,
      bgShow: (!this.data.bgShow),
      lineWidth: 3
    })
    context.setLineWidth(3);
  },
  select_color: function (e) {
    this.setData({
      bgShow: (!this.data.bgShow),
      state: e.currentTarget.dataset.key,
      ftcolor: e.currentTarget.dataset.color
    })
    context.setStrokeStyle(e.currentTarget.dataset.color)
  },
  selectem: function (e) {
    this.setData({
      colorNum: e.currentTarget.dataset.id
    })
    wx.redirectTo({
      url: '../A-index/A-index'
    })
  },
  selectCol: function (e) {
    this.setData({
      bgShow: (!this.data.bgShow),
      colorNum: e.currentTarget.dataset.id
    })
  },
  selectbold: function (e) {
    this.setData({
      bgShow: (!this.data.bgShow),
      colorNum: e.currentTarget.dataset.id
    })
  },
  fbgsClose: function () {
    this.setData({
      bgShow: (!this.data.bgShow)
    })
  },
  selectThis: function (e) {
    this.setData({
      shwoBordr: e.currentTarget.dataset.id,
      bgShow: (!this.data.bgShow)
    });
    noteBg = e.currentTarget.dataset.bg
  },
  // 划线
  changValue: function (e) {
    app.globalData.lineWidth = this.data.lineWidth * e.detail.value;
    this.setData({
      bgShow: (!this.data.bgShow),
      lineWidth: e.detail.value * 1,
      fontValue: e.detail.value
    })
    context.setLineWidth(this.data.lineWidth);
  },
  // 倒计时
  timer () {
    timer = setInterval(() => {
    if (this.data.time > 0) {
      //  this.timerAnimationStart()
        this.setData({
            time: --this.data.time,
            isTouchStart: !(this.data.isTouchStart)
        })
    } else {
        this.timerAnimationStop()
        clearInterval(timer)
    }
  }, 1000)
},
// 初始化动画
timerAnimationInit(){
  animation = wx.createAnimation()
},
  popSharePage: function() {
    app.globalData.source = 4
    wx.redirectTo({
      url: '../previewResul/previewResul?fromQ=fromQ&source=4&special=write'
    })
  },
  // 分享给朋友
  onShareAppMessage: function (ops) {
    const that = this
    if (ops.from === 'button') {
      // 来自页面内转发按钮
    }
    return {
      title: '智慧好字帖',
      path: 'pages/ottShare/ottShare?s&scene=' + that.data.joinRoomMd5,
      // imageUrl:'https://5b0988e595225.cdn.sohucs.com/q_70,c_zoom,w_640/images/20180927/66f237c5d1cb4226af49b4769b34d77d.gif',  //图片
      success: function (res) {
        // 转发成功
        //console.log("转发成功:" + JSON.stringify(res));
        var shareTickets = res.shareTickets;
      },
      fail: function (res) {
        // 转发失败
        //console.log("转发失败:" + JSON.stringify(res));
      }
    }
  },
  openScoket:function(){
    wx.navigateTo({
      url: '../socket/socket'
    })
  },
  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  },
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        if (device.name.indexOf("ZXY") !== -1) {

        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        console.log('============================================')
        console.log(this.data.devices)
        this.setData(data)
      }
      })
    })
  },
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    wx.showLoading({
      title: '等待连接...',
    })
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        wx.hideLoading()
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  drawPenPoint(){
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
      canDraw:true
    })
    //drawIsShow=true;
  },
  penData(){
    drawIsShow = false;
    this.setData({
      connected: true,
      chs: [],
      canWrite: true,
      canDraw: false
    })

  },
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        console.log(res);
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            console.log("getBLEDeviceCharacteristics");
            console.log(deviceId);
            console.log(res.services[i].uuid);
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  },
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            console.log("readBLECharacteristicValue deviceId=",deviceId,"\tserviceid=",serviceId, "\t characteristicId="+item.uuid)
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            console.log("notifyBLECharacteristicValueChange notify|indicate  deviceId=",deviceId,"\tserviceid=",serviceId, "\t characteristicId="+item.uuid+"\t state=true");

            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      console.log("onBLECharacteristicValueChange=",characteristic);
     // const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      uuID=characteristic.characteristicId;
      let unit8Arr = new Uint8Array(characteristic.value);
     // console.log(unit8Arr);
      this.getData(unit8Arr)
      // const data = {}
      // if (idx === -1) {
      //   data[`chs[${this.data.chs.length}]`] = {
      //     uuid: characteristic.characteristicId,
      //     value: ab2hex(characteristic.value)
      //   }
      // } else {
      //   data[`chs[${idx}]`] = {
      //     uuid: characteristic.characteristicId,
      //     value: ab2hex(characteristic.value)
      //   }
      // }
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      //this.setData(data)
    });

    wx.onBLEConnectionStateChange(function (res) {
      // 该方法回调中可以用于处理连接意外断开等异常情况
      // console.log('device ' + res.deviceId + ' state has changed, connected: ' + res.connected);
      console.log('onBLEConnectionStateChange' , res)
      // console.log(res)
      // this.closeBLEConnection()
      if(!res.connected) {
        app.globalData.connectedDeviceId = ''
        app.globalData.connectStatus = false
        wx.showToast({
          title: '已断开设备！',
          icon: 'success',
          duration: 1500,
          success:()=> {
            app.globalData.connectedPenStatus = false
            wx.reLaunch({
              url: '../A-index/A-index',
            })
          }
        })
      }

    });
  },
  drawPoint2Cavas: function () {
    if (pointsCache.length < MAX_CACHE_TO_CANVAS_POINT_NUM) {
      return;
    }
    var points = pointsCache;
    var point;
    console.log("drawPoint2Cavas call.");
    points.forEach((item, index) => {
        point = item;
        // console.log(point)
        if(point.font_color) {
          context.setStrokeStyle(point.font_color)
        }else {
          if(point.color) {
            // console.log(point.color)
            // context.setStrokeStyle('#000')
            context.setStrokeStyle(point.color)
          }else {
            context.setStrokeStyle('#000')
          }
        }
        if(point.font_size) {
          context.setLineWidth(point.font_size);
        }else {
          context.setLineWidth(point.lineWidth);
        }
        switch (point.status) {
          case PenStatus_Move:
            this.drawMove(point.y/penPointH, (penPointW-point.x)/penPointW)
            break;
          case PenStatus_Down:
            this.drawDown(point.y/penPointH, (penPointW-point.x)/penPointW)
            break
          case PenStatus_Up:
            this.drawUp()
            break
      }
      })
    wx.hideLoading({
      complete: (res) => {},
    })
  },
  //解析数据
  drawPoints() {
    let that = this
    // if(app.globalData.lastConnectPage && app.globalData.lastConnectPage != app.globalData.boardIndex) {
      if (app.globalData.boardArray.length) {
        let renderData = app.globalData.boardArray.filter(item => item.boardIndex == app.globalData.boardIndex)
        // console.log(renderData)
        if (renderData.length) {
          // app.globalData.randomNum = renderData[0].page
          // console.log(renderData)
          pointsCache = Array.from(renderData[0].boaderData)
          // console.log(pointsCache)
          that.drawPoint2Cavas()
        }else {
          // app.globalData.randomNum = new Date().getTime();
          // randomPage = app.globalData.lastRandom
        }
      }
        let lastRender = app.globalData.boardArray.filter(item => item.boardIndex == app.globalData.boardIndex)
        console.log(lastRender)
        if (lastRender.length) {
          let arr7 = lastRender[0]
          arr7.boaderData.push(...app.globalData.clientArray)
          app.globalData.boardArray = app.globalData.boardArray.map(item => {
            if (item.boardIndex == arr7.boardIndex) {
              return arr7
            }else {
              return item
            }
          })
          // app.globalData.randomNum = new Date().getTime();
          //console.log(app.globalData.clientArray)
        } else {
          app.globalData.boardArray.push({
            boaderData: app.globalData.clientArray,
            boardIndex: app.globalData.boardIndex
          })
          console.log('app.globalData.boardArray', app.globalData.boardArray)
        }
        app.globalData.clientArray = []
    // }
    
  },

  //last_penStatus(0:hover  1:down 2:move 3:up 4:leave)
  getData(data){
    if (data.length > 0) {
      var num = data.length;
      var index = 0;
      while (index + 10 <= num) {
        var prefix = this.byteToInt1(data[index], data[index + 1]);
        if (prefix == 0xfdfd || prefix == 0xfdfe) {
          var flag = false;
          if (index + 10 == num) {
            flag = true;
          } else if (index + 12 <= num) {
            if (this.byteToInt(data[index + 10], data[index + 11]) == 0xfdfd || this.byteToInt1(data[index + 10], data[index + 11]) == 0xfdfe) {
              flag = true;
            }
          }
          if (flag) {
            var type = (data[index + 2] & 0x0FF);
            var mode = (data[index + 3] & 0x0FF);
            var bleX = this.byteToInt(data[index + 4], data[index + 5]);
            var bleY = this.byteToInt(data[index + 6], data[index + 7]);
            var key = -1;
            //软件按钮
           // console.log("buttonLog", "btnIndex:" + bleX);
            var keyIndex = this.byteToInt(data[index + 5], data[index + 6]);
            //压感
            var blePressure = this.byteToInt(data[index + 8], data[index + 9]);
            index += 10;
            if (mode == 0xa1 || (mode == 0x1 && type == 2)) {
              if (last_penStatus == PenStatus_Hover || last_penStatus == PenStatus_Leave) {
                last_penStatus = PenStatus_Down;
                //console.log("AcionLog", "XYPenStatus_Down");
              } else {
                last_penStatus = PenStatus_Move;
              }
            } else if (mode == 0xa0 || (mode == 0x2 && type == 2)) {
              if (last_penStatus == PenStatus_Down || last_penStatus == PenStatus_Move) {
                last_penStatus = PenStatus_Up;
                //console.log("AcionLog", "XYPenStatus_Move");
              } else {
                last_penStatus = PenStatus_Hover;
              }
            } else if (mode == 0xc0 || (mode == 0x0 && type == 2)) {
              if (last_penStatus == PenStatus_Down || last_penStatus == PenStatus_Move) {
                last_penStatus = PenStatus_Up;
               // console.log("AcionLog", "XYPenStatus_up");
              } else {
                last_penStatus = PenStatus_Leave;
              }
            } else if (mode == 0xf0 || type == 1) {
              if (prefix == 0xfdfe && keyIndex>0) {
                  this.setData({
                    keyIndex: keyIndex
                  })
              } 
            } 
            var filtered = false;
            if (last_penStatus == 0) {
              //if (Math.abs(bleX - last_penX) <= 5 && Math.abs(bleY - last_penY) <= 5) {
                filtered = true;
              //}
            }
            switch(keyIndex){
              case 102://clean
                this.cleardraw()
                strokesHelper.clearOneTian(lastDrawCanvasName);

                console.log("clearDraw");
                app.globalData.randomNum = new Date().getTime();
                oneWordPos = [];
                
              break
              case 104:
                context.setStrokeStyle('#000000');
                this.setData({
                  ftcolor: 'rgb(0,0,0)'
                })
              break
              case 105:
                context.setStrokeStyle('#FF0000');
                this.setData({
                  ftcolor: 'rgb(255,0,0)'
                })
              break
              case 106:
                context.setLineWidth(1);
                this.setData({
                  lineWidth: 1,
                })
              break
              case 103:
                context.setStrokeStyle('#0000F5');
                this.setData({
                  ftcolor: 'rgb(0,0,245)'
                })
              break
              case 107:
                context.setLineWidth(2);
                this.setData({
                  lineWidth: 2,
                })
              break
              case 108:
                context.setLineWidth(3);
                this.setData({
                  lineWidth: 3,
                })
              break
              case 109:
                console.log("对标");
                if(strokesHelper.getPromptRedSlashTmpPath().length > 0){
                  isAdjustRed = true;
                  strokesHelper.showRedPrompt(this, strokesHelper.getPromptRedSlashTmpPath());
                }
                break
              case 111:
                pageNo++;
                if(pageNo > 40){
                  pageNo = 40;
                  break;
                }

                strokesHelper.prepareTianFile(classInfo, pageNo, isAdustPointAlready);
                strokesHelper.clearAllDraw();
                break;
                // console.log('下页' + app.globalData.boardIndex)
                app.globalData.randomNum = new Date().getTime();
                app.globalData.boardIndex = app.globalData.currentIndex
                this.touchend()
                this.cleardraw()
                this.drawPoints()
                app.globalData.currentIndex = app.globalData.boardIndex + 1

                
              break
              case 112:
                pageNo--
                if(pageNo < 1){
                  pageNo = 1;
                  break;
                }

                strokesHelper.prepareTianFile(classInfo, pageNo, isAdustPointAlready);
                strokesHelper.clearAllDraw();

                break;
                app.globalData.randomNum = new Date().getTime();
                app.globalData.boardIndex = app.globalData.currentIndex - 1
                  // console.log('上页' + app.globalData.boardIndex)
                  this.touchend()
                  this.cleardraw()
                  this.drawPoints()
                  app.globalData.currentIndex = app.globalData.boardIndex
                  break
            }

            if (!filtered) {
              last_penX = bleX;
              last_penY = bleY;
              var x=bleY/penPointH;
              var y=(penPointW-bleX)/penPointW;
              if(drawIsShow){
              switch(last_penStatus){
                case PenStatus_Down:
                this.drawDown(x,y)
                break
                case PenStatus_Move:
                this.drawMove(x,y)
                break
                case PenStatus_Up:
                this.drawUp()
                break
              }
             }
              if (!drawIsShow){
                   const data = {
                    connected: true,
                  chs: [],
                    canWrite: true,
              }
              data[`chs[0]`] = {
                uuid: uuID,
                value: "X:" + bleX + " Y:" + bleY + " blePressure:" + blePressure+" penStatus:" + last_penStatus
               }
              this.setData(data)
             }
             if (last_penStatus != 0)
              //  console.log("X:" + bleX + " Y:" + bleY + " blePressure:" + blePressure+" penStatus:" + last_penStatus)
              if(x !== 0 && y !== 0) {
//                console.log(app.globalData.randomNum)
                var clientObjNew = {
                    token: app.globalData.token,
                    x: bleX,
                    y: bleY,
                    font_size: this.data.lineWidth,
                    font_color: this.data.ftcolor,
                    bg_music: app.globalData.globalMusic,
                    bg_img: this.data.canvasbg,
                    status: last_penStatus,
                    pressure: blePressure,
                    connectionType: 'write',
                    timeStamp: new Date().getTime(),
                    canvasw: app.globalData.clientWidth,
                    note_page: app.globalData.randomNum
                }
                app.globalData.clientArray.push(clientObjNew)
                /*
                app.globalData.localSocket.send({
                  data: JSON.stringify(clientObjNew)
                })
                */
              }
            }
          } else {
            index += 2;
          }
        } else {
          index += 1;
        }
      }
    }
  },
   byteToInt( b0,  b1){
    var s = 0;
    var s0 =(b0 & 0xff);// 最低位
    var s1 = (b1 & 0xff);
    s1 <<= 8;
    s = (s0 | s1);
    return s;
  },
  uint8ToStr(arr){
    for(var i = 0, str=''; i<arr.length; i++){
      str += String.fromCharCode(arr[i]);
    }
    return str;
},
  strToUint8(str) {
    for (var i = 0, arr = []; i < str.length; i++) {
      arr.push(str.charCodeAt(i));
    }
    return new Uint8Array(arr);
  },
  byteToInt1( b0,  b1) {
    var s = 0;
    var s0 = (b0 & 0xff);// 最低位
    var s1 = (b1 & 0xff);
    s0 <<= 8;
    s = (s0 | s1);
    return s;
  },
  writeBLECharacteristicValue() {
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, Math.random() * 255 | 0)
    console.log("writeBLECharacteristicValue deviceId=",this._deviceId,"\tserviceid=",this._deviceId, "\t characteristicId=", this._characteristicId,"\tval=",buffer)

    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._deviceId,
      characteristicId: this._characteristicId,
      value: buffer,
    })
  },
  closeBluetoothAdapter() {
    console.log("closeBluetoothAdapter")
    wx.navigateBack({
      delta: 1
    })
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },
  //初始化画布
  initCanvas: function () {
    console.log("initCanvas")
    var that = this;
    // 使用 wx.createContext 获取绘图上下文 context
    context = wx.createCanvasContext('partyCanvas');
    context.beginPath()
    context.setStrokeStyle('#000000');
    context.setLineWidth(2);
    context.setLineCap('round');
    context.setLineJoin('round');
    wx.getSystemInfo({
      success: function (res) {
        canvasw = res.windowWidth;//设备宽度
        canvash = res.windowHeight;//res.windowWidth * 1.43;
        console.log("屏幕w:",canvasw)
        console.log("屏幕h:", canvash)
      }
    });
  }, 
  // 查看用户是否授权
  getUserInfo:function(){
     var that=this
     // 登录
     wx.login({
      success: res => {
        if (res.code) {
          that.setData({
            code:res.code
          })
          // 查看是否授权
          wx.getSetting({
            success: function (res) {
              if (res.authSetting['scope.userInfo']) {
                that.setData({
                  hasAuthorize:true
                })
                wx.getUserInfo({
                  success: res => {
                    console.log(res)
                    wx.setStorage({
                      key: 'userInfo',
                      data: res.userInfo,
                    })
                    app.globalData.userInfo = res.userInfo;
                    that.setData({
                      avator:app.globalData.userInfo.avatarUrl
                    })
                    userSocket.linkSocket(1) //连接websocket 1为授权用户
                  }
                })
              }else{
                userSocket.linkSocket(0) //连接websocket 0为游客
                that.setData({
                  hasAuthorize:false
                })
              }         
            }
          })
        }
      }
     })
  },
  // 用户授权
  bindGetUserInfo: function (e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      that.setData({
        hasAuthorize:true
      })
      this.getUserInfo() //查询存储用户信息
    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，无法进行更多操作!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击了“返回授权”')
          }
        }
      })
    }
  },
  // 聊天消息
  getchatmsg:function(e){
    this.setData({
      doodlemsg:e.detail.value
    })
  },
  // 发送消息
  sendchat:function(type){
    var msg = this.data.doodlemsg.replace(/(^\s*)|(\s*$)/g, "")
    if(msg!==''){
      this.setData({         
        doodlemsg:''
      })
      wx.showToast({
        title: '发布成功',
        icon: 'none',
        duration: 3000//持续的时间
      })
      userSocket.sendChat(msg)   
    }  
  },
  // 唤起键盘
  keyboardFocus:function(){
    this.setData({
      beforeFocus:this.data.chatBtn_default,
      chatBtn_default:2
    })
  },
  // 键盘收起
  chatBlur:function(){
    this.setData({
      chatBtn_default:this.data.beforeFocus
    })
  },
  // 查看消息记录
  chatListShow:function(){
    this.setData({
      chatBtn_default:3,
      showChatList:true
    })
  },
  // 隐藏消息记录
  hideChatList:function(){
    this.setData({
      chatBtn_default:1,
      showChatList:false
    })
  },
  // 每一笔笔记消息
  singleDraw(msg){
      if(msg &&
         msg.length < 1
      ){
         return;
      }

      var onePos = msg.shift();
      if(onePos == "stream")
      {
        this.drawing(msg);
      }else if(onePos == "ctrl")
      {
        this.cmdAct(msg);
      }
  },

  cmdAct(act){
      if(act == "clear"){
        this.cleardraw()
        strokesHelper.clearOneTian(lastDrawCanvasName);

        console.log("clearDraw");
        app.globalData.randomNum = new Date().getTime();
        oneWordPos = [];
      }
  },

  drawing(msg){
    var onePos = msg.shift();
    this.drawDown(onePos[0],onePos[1]);
      
    msg.forEach((item) => {
      this.drawMove(item[0],item[1]);
    });

    this.drawUp();
  },

  singleDrawOld(msg){
    var oneStroke = [];
    msg.forEach((item) => {
           var oneP = new strokesHelper.StrokesStore();//{beginP:{x:0,y:0}};
           oneP.beginP.x = item[0];
           oneP.beginP.y = item[1];
           oneStroke.push(oneP);
    });
    oneWordPos.push(oneStroke);
     var needClearStroke = strokesHelper.drawUp(oneWordPos,this);
     if(needClearStroke){
       oneWordPos = [];
     }
     oneStroke = [];
  },

  // 显示消息操作内容
  showAction:function(e){
    var id=e.currentTarget.dataset.id,
        index=e.currentTarget.dataset.index
    var canAction = 'chatlist[' + index+ '].canAction'
    this.setData({
      [canAction]: true,
      chatlist:this.data.chatlist
    })
    console.log(this.data.chatlist)
  },
  // 复制消息信息
  copyText: function (e) {
    var that=this
    console.log(e)
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            var index=e.currentTarget.dataset.index
            var canAction = 'chatlist[' + index+ '].canAction'
            that.setData({
              [canAction]: false
            })
          }
        })
      }
    })
  },
  // 删除消息
  delText:function(e){
    var id=e.currentTarget.dataset.msgid
    userSocket.delmsg(id)   
    var index=e.currentTarget.dataset.index
    var canAction = 'chatlist[' + index+ '].canAction'
    this.setData({
      [canAction]: false
    })
  },
  // 关闭点赞提示框
  closeCuePraise:function(){
    this.setData({
      cuePraise:false
    })
  },
  // 时间戳转换成年月日时分
  toTime:function(inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '年' + m + '月' + d + '日 ' + h + ':' + minute;
  },
  onReady:function() {
  },
  onLoad: function (options) {
    console.log("onLoad");
    var that=this
    wx.setNavigationBarTitle({
      title: '智慧好字帖'
    }) 

    if(options.hasOwnProperty('s'))
    {
      this.data.isShareZone = true;
    }
    //this.data.isShareZone = true;

    var getMd5 = decodeURIComponent(options.scene) 
    if (getMd5 && getMd5!=='undefined') {
      this.setData({
        joinRoomMd5:getMd5
      })     
    }
    userSocket.getMainThis(this);
    this.getUserInfo()  //查看用户是否授权
    console.log("屏幕尺寸："+app.globalData.clientWidth+","+
    app.globalData.clientHeight);
    strokesHelper.showRedPrompt(this, '');
    strokesHelper.setOffsetPos(0,0);
    wx.getSystemInfo({
      success: function (res) {
        console.log(res)
        //model中包含着设备信息
        var model = res.model
        app.globalData.clientWidth = res.windowWidth
        app.globalData.clientHeight = res.windowHeight
        app.globalData.globalSize = res.windowWidth * 1.43
        app.globalData.ratioX = res.windowWidth / 63.9
        app.globalData.ratioY = res.windowWidth * 1.45 / 92
        app.globalData.paddingClient = (res.windowHeight - res.windowWidth * 1.43 - 66) / 2
        app.globalData.constant = res.windowWidth/375
        app.globalData.constanth = res.windowHeight/667
        that.setData({
          clientSize: app.globalData.globalSize,
          paddingClient: app.globalData.paddingClient,
          clientWidth:app.globalData.clientWidth,
          clientHeight:app.globalData.clientHeight,
        })
      }
    })
    app.initEventHandlePen()
    let isPhone = app.globalData.isIpx;
    if (isPhone) {
      this.setData({
        btuBottom: "10rpx 0 90rpx",
        wImage: app.globalData.constant * 57,
        hImage: app.globalData.constant * 57,
        tImage: app.globalData.constant * 110,
        lImage: app.globalData.constant * 35,
        wText: app.globalData.constant * 35,
        hText: app.globalData.constant * 35,
        tText: app.globalData.constant * 134,
        lText: app.globalData.constant * 150
      })
    }else {
      this.setData({
        btuBottom: "10rpx 0 70rpx",
        wImage: app.globalData.constant * 57,
        hImage: app.globalData.constant * 57,
        tImage: app.globalData.constant * 46,
        lImage: app.globalData.constant * 35,
        wText: app.globalData.constant * 35,
        hText: app.globalData.constant * 35,
        tText: app.globalData.constant * 68,
        lText: app.globalData.constant * 155
      })
    }

    //console.log(options)
    app.globalData.lastRandom = ''
    
    this.setData({
      canvasbg: app.globalData.canvasbg ? app.globalData.canvasbg : 'https://wx.ndmooc.com/files/moban/bg02.png',
      // canvasbg: 'https://wx.ndmooc.com/files/wximg/8.jpg',
      mp3: app.globalData.globalMusic,
      // avatarImg: app.globalData.userInfo.avatarUrl,
      // avatarImg:'https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoQ2OiawMmW2NaibpmyOtaGibB5TAkPZvkVic3xKO45qDEpYwkTuNZKLwI7LKFx3CAW0tVMhydLGteiaFg/132',
      // username: app.globalData.userInfo.nickName
      // username: 'toon'
    })
    console.log(this.data.canvasbg)
    console.log(options.fromQ)
    if(options.fromQ !== 'fromQ') {
      app.globalData.clientArray = []
      app.globalData.randomNum = new Date().getTime();
    }else {
      console.log(app.globalData.page)
      app.globalData.randomNum = app.globalData.page
      pointsCache = app.globalData.clientArray
      // console.log(pointsCache)
      this.drawPoint2Cavas()
    }

    innerAudioContext.src = app.globalData.globalMusic
    innerAudioContext.onPlay(() => {
      that.setData({
        bgm: true,
        bgmImgAni: "bgmImgAni"
      })
    })
    WXAPI.settingNew({
      token: app.globalData.token,
      bluetooth: [{
        'dataType': app.globalData.connectionType,
        'dataUuid': app.globalData.devicePenID,
        'dataName': app.globalData.devicedName
      }]
    }).then(res => {
      //console.log(res)
    })
    wx.getStorage({
      key: 'userInfo',
      success(res){
        console.log(res)
        that.setData({
          username: res.data.nickName ? res.data.nickName : app.globalData.userInfo.nickname,
          avatarImg: res.data.avatarUrl ? res.data.avatarUrl : app.globalData.userInfo.avatar,
        })
      },
      fail(err) {
        that.setData({
          username: app.globalData.userInfo.nickname,
          avatarImg: app.globalData.userInfo.avatar,
        })
      }
    })
    
    //strokesHelper.pcTestCousrFromFirst(this);
    
  },
  onShow() {
    // app.globalData.clientArray = []
    saving = false
    onlyOnce = 0
    app.globalData.lastConnectPage = 1
    if (wx.getScreenBrightness) {
      //获取屏幕亮度 值：0-1，越大越亮
      wx.getScreenBrightness({
        success: function (res) {
          // res.value
          app.globalData.screenLight = res.value
        },
        fail: function () {
          //请求失败 
        }
      })
    } else {
    }
    if (wx.setScreenBrightness) {
      // 保持屏幕常亮 true / false
      wx.setScreenBrightness({
        value: 0.3,
        success: function (res) {
          wx.setKeepScreenOn({
            keepScreenOn: true,
            success: function (res) {
            }
          });
        }
      });
    } else {

    }

    this.initCanvas();

    this.setData({
      mp3: app.globalData.globalMusic
    })
  },
  /**
   * 长按录音开始
   */
  recordStart: function(e) {
    let that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success () {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              // wx.startRecord()
              that.setData({
                recodeFile: true,
                recoderAuthStatus: true
              })
              that.recorderManagerStart(e);
            },
            fail: function() {
              console.log("第一次录音授权失败");
              wx.showModal({
                title: '提示',
                content: '您未授权录音，功能将无法使用',
                showCancel: true,
                confirmText: "授权",
                confirmColor: "#52a2d8",
                success: function (res) {
                  if (res.confirm) {
                    //确认则打开设置页面（重点）
                    wx.openSetting({
                      success: (res) => {
                        console.log(res.authSetting);
                        if (!res.authSetting['scope.record']) {
                          //未设置录音授权
                          console.log("未设置录音授权");
                          wx.showModal({
                            title: '提示',
                            content: '您未授权录音，功能将无法使用',
                            showCancel: false,
                            success: function (res) {

                            },
                          })
                        } else {
                          //第二次才成功授权
                          console.log("设置录音授权成功");

                          //开始录音
                          // recorderManager.start(options);
                          // recorderManager.onStart(() => {
                          //   // 开始录音显示loading
                            
                          //   console.log('recorder start')
                          // });
                          that.setData({
                            recodeFile: true,
                            recoderAuthStatus: true
                          })
                          that.recorderManagerStart(e);
                          //错误回调
                          // recorderManager.onError((res) => {
                          //   console.log('recorder error')
                          // })
                        }
                      },
                      fail: function () {
                        console.log("授权设置录音失败");
                      }
                    })
                  } else if (res.cancel) {
                    console.log("cancel");
                  }
                },
                fail: function () {
                  console.log("openfail");
                }
              })
            }
          })
        }else {
          that.setData({
            recodeFile: true,
            recoderAuthStatus: true
          })
          that.recorderManagerStart(e);
        }
      }
    })
    // if(that.data.recoderAuthStatus) {
    //   that.setData({
    //     recodeFile: true
    //   })
    //   that.recorderManagerStart(e);
    // }else {
   
      // wx.authorize({
      //   scope: "scope.record",
      //   success: function() {
      //     console.log("录音授权成功");
      //     that.setData({
      //       recodeFile: true,
      //       recoderAuthStatus: true
      //     })
      //     that.recorderManagerStart(e);
      //   },
      //   fail: function() {
      //     console.log("录音授权失败");
      //   }
      // })
    // }
      
    //   if (that.data.recoderAuthStatus) {
    //     that.recorderManagerStart();
    // } else {
    //     wx.authorize({
    //         success(res) {
    //           console.log(res)
    //             if (res.authSetting["scope.record"]) {
    //                 that.setData({
    //                   recoderAuthStatus: true
    //                 })
    //                 that.recorderManagerStart();
    //             }
    //         }
    //     });
    // }
    
  },

  recorderManagerStart: function(e) {
    console.log(e)
    var n = this;
        rm.start({
          format: "mp3",
          sampleRate: 32e3,
          encodeBitRate: 192e3
        }), n.setData({
          touchStart: e.timeStamp,
          showPg: true,
          isTouchStart: true,
          isTouchEnd: false
        })
        var a = 600000, o = 10;
        n.timerAnimationInit()
        n.timer()
        // n.timer = setInterval(function () {
        //   // n.setData({
        //   //   value: n.data.value - 1000 / 600000,
        //   // }),
        //   // (o += 10) >= 1e3 && o % 1e3 == 0 && (
        //   //   a-- , 
        //   //   a <= 0 && (
        //     rm.stop(),
        //     // clearInterval(n.timer), n.animation2.scale(1, 1).step(), 
        //     n.setData({
        //       // animationData: n.animation2.export(),
        //       isTouchStart: false,
        //       isTouchEnd: true
        //     })
        //     // )
        //     // );
        // }, 10);
  },
  touchend(e) {
    innerAudioContext.stop()
    let that = this;
    innerAudioContext.stop()
    that.setData({
      slider: true,
      bgm: false,
      imgTurn: true
    });
    //创建动画   5s将位置移动到-150%,-150%
    let animation = wx.createAnimation({
      duration: 3000,
    });
    animation.translateX('-150%').translateY('-150%').rotate3d(60).step();
    that.setData({
      animationData: animation.export()
    });

    // 移动完成后
    setTimeout(function () {
      //创建动画   将位置归位
      let animation = wx.createAnimation({
        duration: 0,
      });
      animation.translateX('-53%').translateY('-50%').rotate(0).step();
      that.setData({
        animationData: animation.export(),
        slider: false,
        imgTurn: false
      });
      innerAudioContext.stop()
    }, 500)
  },
  /**
   * 长按录音结束
   */
  recordTerm: function(e) {
    this.setData({
      recodeFile: false
    })
    rm.stop();
    console.log(rm)
    this.setData({
        isTouchEnd: true,
        isTouchStart: false,
        touchEnd: e ? e.timeStamp : '',
        showPg: false,
        value: 100
      });
    clearInterval(this.timer);
    clearInterval(timer)
  },

  onUnload:function(){
    this.recordTerm()
    innerAudioContext.stop();
    this.cleardraw()
    app.closeBook()
  },
  drawDown(x,y){
    lastX = x * canvasw;
    lastY = y * canvash;
    
    // if(isAdjustRed){
    //   isAdustPointAlready = true;
    //   strokesHelper.ding();
    //   if(!isSingleanchor){
    //       prepareAdjustPoint.push({x:x,y:y});
          
    //       if(prepareAdjustPoint.length == 2){
    //         strokesHelper.setOffsetPosTwo(prepareAdjustPoint);
    //         strokesHelper.showRedOKPrompt(this, strokesHelper.getPromptRedOKTmpPath());
    //         isAdjustRed = false;
    //         prepareAdjustPoint = [];
    //       }
    //   }else{
    //       strokesHelper.setOffsetPos(x,y);
    //       strokesHelper.showRedOKPrompt(this, strokesHelper.getPromptRedOKTmpPath());
    //       isAdjustRed = false;
    //   }
    //   this.cleardraw();
    //   return;
    // }

    var name;
    if(!isSingleanchor){
        name = strokesHelper.getTianNameByPosTwo(x,y);
    }else{
        name = strokesHelper.getTianNameByPos(x,y);
    }
    
    if(name.length > 0){
        console.log("写在区域内，格子名称："+name);

        if(lastDrawCanvasName != name &&
           lastDrawCanvasName.length > 0  
        ){
          strokesHelper.focusDrawUpByCanvasName(oneWordPos,this, lastDrawCanvasName);
          oneWordPos = [];
          this.setData({ word_comment: ""});
        }

        oneStroke = [];
        if(oneWordPos.length == 0 &&
           name.length != 0  
        ){
          //落笔如果没有写入，那么就清除之前的
          strokesHelper.clearOneTian(name);
        }
    }
    lastDrawCanvasName = name;
    
    var offzzz = strokesHelper.getOffsetPoxByXY(x,y);
    console.log('drawDown:\t"x":'+offzzz[0]+',"y":'+offzzz[1]);
    /*
    if(strokesHelper.isSetOffsetPos()){
      var getOffsetPox = strokesHelper.getOffsetPoxByXY(x,y);
      //console.log("相对位置");
      //console.log('"x":'+getOffsetPox[0]+',"y":'+getOffsetPox[1]);
    }
    */
    // this.has = [];
    // this.upof = this.getXY(x,y);
  },
  drawMove(x,y,p){
    console.log("drawMove:x="+x+"\ty="+y);
    var ex = x * canvasw;
    var ey = y * canvash;
    
    if(lastX<0){
      lastX = ex;
      lastY = ey;
    }

    var contX=(lastX+ex)/2;
    var contY=(lastY+ey)/2;

    context.beginPath();
    context.moveTo(lastX, lastY);
    context.lineTo(ex, ey);
    context.quadraticCurveTo(contX,contY,ex,ey);
    context.stroke();
    context.draw(true);
    lastX = ex;
    lastY = ey;

    if(lastDrawCanvasName.length > 0){
        var oneP = new strokesHelper.StrokesStore();
        oneP.beginP.x = ex;
        oneP.beginP.y = ey*0.7070707070707071;//来自1:1.4 补偿の问候咩
        oneP.beginP.xorig = x;
        oneP.beginP.xorig = y;
        //oneP.penWidth = 2;
      
        oneStroke.push(oneP);
    }
  },
  drawUp(){
    console.log("drawUp");
    lastX=-1;
    lastY=-1;
    
    if(lastDrawCanvasName.length > 0){
        if(oneStroke.length > 0)
          oneWordPos.push(oneStroke);

        var needClearStroke = strokesHelper.drawUp(oneWordPos,this);
        if(needClearStroke){
          oneWordPos = [];
        }

        oneStroke = [];
    }
  },

  getXY(x,y) {
    console.log(x,y)
    // console.log(e)
    // return {
    //   x: e.touches[0].x - (this.canvas.offsetLeft || 0) + (this.viewBox.scrollLeft || 0),
    //   y: e.touches[0].y - (this.canvas.offsetTop || 0) + (this.viewBox.scrollTop || 0)
    // }
    return {
      x: x,
      y: y
    }
  },

  downloadTraceFile(){
    console.log("downloadTraceFile");
    var url = 'https://wx.ndmooc.com/files/fontdata/'+this.data.roomid+'.trace';
    console.log(url);
    var tp = this;
    wx.request({
      url: url,
      success (res) {
            if(res.statusCode == 200){
              if(res.data.length<0) return;

              var msg = res.data.split("\r\n");
              var allStreaming = [];

              msg.forEach((item) => {
                  var oneLine = item.replace('],]',']]');
                  oneLine.trim();
                  if(oneLine.length < 2){
                      return;
                  }
                  
                  console.log(oneLine);
                  //var oneS = JSON.parse(oneLine);
                  allStreaming.push(oneLine);
              }); 
              
              console.log("downloadTraceFile:");
              console.log(allStreaming);
              if(allStreaming.length>0){
                  if(tp.data.isShareZone){
                      tp.drawingMyStreaming(allStreaming,tp);
                  }else{
                    tp.data.isShareZone = true;
                    StrokesHelper.clearAllTian();
                    allStreaming.forEach(oneLineR => {
                        var oneLine =  JSON.parse(oneLineR);
                        //tp.singleDraw(oneLine);
                    });
                    tp.data.isShareZone = false;
                  }
              }
            }
        }
    });
  },

  drawingMyStreamingInter(){
      var oneLine =  JSON.parse(this.data.myStreaming[this.data.curDrawingPos]);
      console.log("drawingMyStreaming:"+this.data.curDrawingPos);
      console.log(oneLine);
      this.singleDraw(oneLine);

      this.data.curDrawingPos++;
      if(this.data.curDrawingPos >= this.data.myStreaming.length){
          clearInterval(this.drawingMySHandler);

          console.log("restart clearAllTian");
           StrokesHelper.clearAllTian();
           this.data.curDrawingPos = 0;

           this.drawingMySHandler = setInterval(this.drawingMyStreamingInter, this.data.intervalTime);
      }
  },

  drawingMyStreaming(allStreaming){
    clearInterval(this.drawingMySHandler);
    this.data.myStreaming = allStreaming;
    this.data.curDrawingPos = 0;
    StrokesHelper.clearAllTian();

    this.data.intervalTime = 200;

    this.drawingMySHandler = setInterval(this.drawingMyStreamingInter, this.data.intervalTime);
  },

  distance(a, b) {
    let [x, y] = [b.x - a.x, b.y - a.y];
    return Math.sqrt(x * x + y * y);
  },
  
  cleardraw: function () {
    //清除画布
    context.clearRect(0, 0, canvasw, canvash);
    context.draw(true);
  },
 
  dupinyin:function(event){
    strokesHelper.dupinyin(event.currentTarget.dataset.pinyin);
  },


  scroll:function(e) {
    console.log(e)
  },

  reanimationword:function(e){
    // 允许从相机和相册扫码
    /*
    
    */
    strokesHelper.initAnimationWord(e.currentTarget.dataset.idx);//画拼音
    strokesHelper.dupinyin(e.currentTarget.dataset.pinyin); 
  },
  likeword:function(e){
    console.log(e)
    if(this.data.chatBtn_default!==2){
      var animation = wx.createAnimation({  
        duration: 0,  
      })  
      var smallAnimation = wx.createAnimation({  
        duration: 0,  
      }) 
      animation.opacity(1).scale(1, 1).step();//修改透明度,放大 
      smallAnimation.opacity(1).scale(1, 1).step();//修改透明度,放大 
      this.setData({
        'spreakingAnimation': animation.export(),
        'smallAnimation':  smallAnimation.export()
      });
      userSocket.sendHeart(e.currentTarget.dataset.id);  //发送点赞socket消息
      strokesHelper.giveLike(e.currentTarget); //点赞
    }   
  },
  hideredprompt :function(e){
      if(!strokesHelper.isSetOffsetPosTwo()){
          //如果没设置点就退出不隐藏
          return;
      }

      strokesHelper.hideRedPrompt(this);
      isAdjustRed = false;

      this.cleardraw();

  },
  getWordComment:function(e){
    //strokesHelper.showRedPrompt(this, "https://wx.ndmooc.com/files/fontdata/panfen.jpg");
    wx.showToast({
      title: '正在紧张测试当中...',
      icon: 'none',
      duration: 2000//持续的时间
    })
  },

  promptRCPrompt:function(e){
    if(strokesHelper.getPromptRedSlashTmpPath().length > 0){
      isAdjustRed = true;
      strokesHelper.showRedPrompt(this, strokesHelper.getPromptCameraOrTmpPath());
      strokesHelper.clearAllDraw();
    }

    setTimeout(function(){
      strokesHelper.prepareTianFile(1, 3);
      // wx.scanCode({
      //   success(res) {
      //     var matchInfo = res.result.match(/class:(\d+),pageno:(\d+)/i);
      //     if(matchInfo != null){
      //         classInfo =  matchInfo[1];
      //         pageNo = matchInfo[2];

      //         strokesHelper.prepareTianFile(classInfo, pageNo);
      //     }else{
      //       wx.showToast({
      //         title: '扫码失败了',
      //         icon: 'none',
      //         duration: 3000
      //       });
  
      //       //promptRCPrompt();
      //     }
      //   },
      //   fail: (res) =>{
      //     console.log(res);
      //     wx.showToast({
      //       title: '扫码失败了',
      //       icon: 'none',
      //       duration: 3000
      //     });

      //     promptRCPrompt();
      //   }
      // });
    }, 3000);
    
  },
})

var lastX;
var lastY;

var context = null;// 使用 wx.createContext 获取绘图上下文 context
var canvasw = 480;//画布宽度
var canvash = 600;//画布高度
var penPointW = 21000;
var penPointH = 14800;